import React from 'react';
import { message } from 'antd';
import userStorage from '../../utils/storage';

import { APIUrl } from 'src/services/createServices';

export default class UploadComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      loading: false,
      fileUrl: '',
    };
    this.action = `${APIUrl}/file/upload`;
    this.uploadOptions = {
      name: 'file',
      action: this.action,
      headers: { token: userStorage.token },
      beforeUpload: this.beforeUpload,
    };
  }
  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  beforeUpload = (file) => {
    const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isImg) {
      message.error('请上传图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('不能超过2MB!');
    }
    return isImg && isLt2M;
  };
  uploadChange = (info) => {
    return new Promise((resolve) => {
      console.log(info);
      if (info.file.status === 'uploading') {
        this.setState({ loading: true });
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        if (info.file.response.error === 1) {
          message.error('上传失败!');
          this.setState({ loading: false });
        } else if (info.file.response.error === 0) {
          this.getBase64(info.file.originFileObj, (imageUrl) =>
            this.setState({
              imageUrl,
              loading: false,
            })
          );
          resolve(info.file.response.url);
        }
      }
    });
  };
}
